package net.huashitong.supervision.excel.ctrl;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysDeptFilter;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.excel.Entity.ExcelDataEntity;
import net.huashitong.supervision.excel.filter.ExcelDataFilter;
import net.huashitong.supervision.excel.service.ExcelDataService;
import net.huashitong.supervision.gongjian.dto.FeedBackDTO;
import net.huashitong.supervision.insideDuCha.entity.InsideMainTaskEntity;
import net.huashitong.supervision.insideDuCha.filter.InsideMainTaskFilter;
import net.huashitong.supervision.insideDuCha.util.CommUtil;
import net.huashitong.supervision.task.entity.TaskUnit;
import net.huashitong.util.DateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/excel/data")
public class ExcelDataCtrl extends JsonBaseController {

    @Autowired
    @Lazy(true)
    private ExcelDataService excelService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysDeptService sysDeptService;

    @Value("${wen.template}")
    private String excelpath;

    @Override
    protected String getView(String s) {
        return "/modules/task/excelData/"+s;
    }


    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/import")
    public String allTask(Model model){

        // model.addAttribute("deptId", SysUserUtils.getDeptId());
        return getView("/query");
    }


    @ResponseBody
    @RequestMapping(value = "/getFailList", method = RequestMethod.GET)
    public Message getFailList(String batchNum){

        if(ObjectUtils.isBlank(batchNum))
        {
            return coverMessage("500","批次号不能为空");
        }
        List<ExcelDataEntity> byBatchNum = excelService.getByBatchNum(batchNum);

        byBatchNum=byBatchNum.stream().filter(entity -> entity.getFlags()==0).collect(Collectors.toList());
        List<String> ids = new ArrayList<>();
        for (ExcelDataEntity entity : byBatchNum) {
            ids.add(entity.getSysId());
        }
        HashMap<String,Object> map  = new HashMap<>();
        map.put("failList",ids);

        return  coverMessage("200","获取成功",map);
    }


    /**
     * 查看数据
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public JqGrid initAllTasks(@ModelAttribute ExcelDataFilter filter){


        List<ExcelDataEntity> byBatchNum = excelService.getByBatchNum(filter.getBatchNum());
      /*  if(ObjectUtils.isNotBlank(byBatchNum)){

            for (ExcelDataEntity entity : byBatchNum) {
                String cell6 = entity.getCell6();
                String depts = getdeptName(cell6);
                entity.setCell1(depts);

                String cell7 = entity.getCell7();
                String xiebanNames = getdeptName(cell7);
                entity.setCell2(xiebanNames);

                String cell8 = entity.getCell8();
                String leaderName = getLeaderName(cell8);
                entity.setCell5(leaderName);
            }

        }*/
        for (ExcelDataEntity entity : byBatchNum) {
            if(StringUtils.isNotBlank( entity.getCell10()))
            {
                String depts = getdeptName(entity.getCell10());
                entity.setCell9(depts);

            }

            String cell6 = entity.getCell6();
            if(ObjectUtils.isNotBlank(cell6))
            {

                String depts = getdeptName(cell6);
                entity.setCell1(depts);
            }
            String cell7 = entity.getCell7();

            if(ObjectUtils.isNotBlank(cell7))
            {
                String xiebanNames = getdeptName(cell7);
                entity.setCell2(xiebanNames);

            }


        }
        Collections.reverse(byBatchNum);
        return  coverJqGrid(filter,byBatchNum);
    }

    private String getdeptName(String deptiId){
        if(StringUtils.isBlank(deptiId))
        {
            return "";
        }
        String[] split = deptiId.split(",");
        String deptaName ="";
        for (String s : split) {
            SysDept byId = deptService.getById(s);
            deptaName=deptaName+byId.getDeptName()+",";
        }
        return deptaName;
    }
    private  String getLeaderName(String  leadIds)
    {
        if (StringUtils.isBlank(leadIds))
        {
            return "";
        }
        String names ="";
        String[] split = leadIds.split(",");
        for (String s : split) {
            SysUser lead = sysUserService.getById(s);
            names=names+lead.getName();
        }
        return names;
    }

    /**
     * 修改和校验数据
     * @param datebean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute ExcelDataFilter datebean) {

        ExcelDataEntity entity = excelService.getById(datebean.getSysId());
        entity.setFlags(1);
        entity.setCell0(datebean.getCell0());//事件
        entity.setCell1(datebean.getCell1());//牵头单位中文  、承办人
        entity.setCell2(datebean.getCell2());//协办单位中文
        if(StringUtils.isBlank(datebean.getCell3())||StringUtils.isBlank(datebean.getCell4()))
        {
            return  coverMessage("500","更新失败，时限和周期类型不能为空");

        }
        entity.setCell3(datebean.getCell3());//周期类型
        if("周".equals(datebean.getCell3()))
        {
            if(!datebean.getCell4().startsWith("星期")){

                datebean.setCell4( DateUtil.IntToWeek(datebean.getCell4()));
            }else {
                int i = DateUtil.weekToInt(datebean.getCell4());
                if(i==0){
                    return coverMessage("500","更新失败，周期类型错误，请正确填写");
                }
            }
        }
        entity.setCell4(datebean.getCell4());//时限
        //校验时限和周期类型
        entity.setCell5(datebean.getCell5());//抄送领导
        if(StringUtils.isBlank(datebean.getCell6()))
        {
            return  coverMessage("500","更新失败，承办单位（人）不能为空");

        }
        entity.setCell6(datebean.getCell6());//牵头单位id 、 承办人id
        entity.setCell7(datebean.getCell7());//协办单位id

        if (excelService.containSameId(datebean.getCell6(),datebean.getCell7())) {
            return coverMessage("500","牵头单位和协办单位不能为同一个");
        }

        entity.setCell8(datebean.getCell8());//抄送领导id
        //督查组
        entity.setCell9(datebean.getCell9());
        entity.setCell10(datebean.getCell10());



        //时间校验，
        String s = excelService.matchTimeType(entity.getCell3(), datebean.getCell4());
        if(""!=s)
        {
            return coverMessage("500", "更新失败,"+s);
        }




        entity.setRemarks("已手动修改数据");
        excelService.update(entity);
        return  coverMessage("200","修改成功");
    }


    /**
     * 普通立项的修改 -打开页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/checkAndUpdate")
    public String showEditView(Model model,String batchNum) {
       /* System.out.println(id);
        ExcelDataEntity ent = excelService.getById(id);

        String cell6 = ent.getCell6();
        String depts = getdeptName(cell6);
        ent.setCell1(depts);

        String cell7 = ent.getCell7();
        String xiebanNames = getdeptName(cell7);
        ent.setCell2(xiebanNames);

        model.addAttribute("excelData",ent);*/
        ExcelDataEntity ent= new ExcelDataEntity();
        ent.setBatchNum(batchNum);
        model.addAttribute("excelData",ent);
        return getView("edit_form");
    }

    /**
     * 普通立项的修改根据id 获取数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getById")
    public Message getById(@RequestBody ExcelDataFilter filter) {
        if(StringUtils.isBlank(filter.getSysId()))
        {
            return  coverMessage("500","sysId不能为空");
        }
        System.out.println(filter.getSysId());
        ExcelDataEntity ent = excelService.getById(filter.getSysId());
        return coverMessage("200", "操作成功", ent);
    }




    /**
     * 导入普通立项
     * @param excelFile
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Message taskExcel(@RequestParam MultipartFile excelFile, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        String name = excelFile.getOriginalFilename();
        String msg="";
        List<ExcelDataEntity> excelDataEntities =null;
        HashMap<String ,Object> resultMap = new HashMap<>();
        List<String> failLst = new ArrayList<>();
        if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
            System.out.println("文件不是excel类型");
            return coverMessage("500", "文件类型错误");
        } else {
            // String s = taskMainService.taskExcel(excelFile.getInputStream(), name);

            try {
                excelDataEntities = excelService.importDatas(excelFile.getInputStream(), null);
                if(null==excelDataEntities)
                {
                    resultMap.put("batchNum","error");
                    resultMap.put("failList",failLst);
                    String meg = "表头校验失败";
                    return coverMessage("200",meg,resultMap);
                }else {

                    excelDataEntities = excelService.saveData(excelDataEntities);
                }

            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }



            List<ExcelDataEntity> collect = excelDataEntities.stream().filter(entity -> entity.getFlags() == 0).collect(Collectors.toList());
            collect.forEach(entity -> {
                failLst.add(entity.getSysId());
            });
            msg = redisService.get("batchNum:" + SysUserUtils.getUserId());//获取批次号
            resultMap.put("batchNum",msg);
            resultMap.put("failList",failLst);
            String meg = "导入成功！本次导入"+excelDataEntities.size()+"条，校验不通过"+failLst.size()+"条";
            return coverMessage("200",meg,resultMap);
        }
    }

    /**
     * -----------内部立项导入 ------------
     */
    /**
     * 内部立项导入Excel
     * @param excelFile
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/insideImportExcel", method = RequestMethod.POST)
    public Message insideExcel(@RequestParam MultipartFile excelFile, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        String name = excelFile.getOriginalFilename();
        String num="";
        List<ExcelDataEntity> list=null;
        if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
            System.out.println("文件不是excel类型");
            return coverMessage("500","文件类型错误");
        }else {
            try {
                 list = excelService.insideImportDatas(excelFile.getInputStream(), "");
                list = excelService.saveInsideDataDeal(list);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
        }
        List<String > failList = new ArrayList<>();
        HashMap<String ,Object> resultMap = new HashMap<>();
        List<String> failLst = new ArrayList<>();
        List<ExcelDataEntity> collect = list.stream().filter(entity -> entity.getFlags() == 0).collect(Collectors.toList());
        collect.forEach(entity -> {
            failList.add(entity.getSysId());
        });
        num = redisService.get("insideBatch:" + SysUserUtils.getUserId());//获取批次号

        resultMap.put("batchNum",num);
        resultMap.put("failList",failList);

        return coverMessage("200","操作成功",resultMap);
    }


    @RequestMapping(value = "/inside")
    public String inside(Model model){

        // model.addAttribute("deptId", SysUserUtils.getDeptId());
        return "/modules/task/insideExcel/query";
    }


    /**
     * 内部立项查询
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/inside", method = RequestMethod.POST)
    public JqGrid initInsideData(@ModelAttribute ExcelDataFilter filter){

        // filter.setBatchNum("1609898334041");
        List<ExcelDataEntity> byBatchNum = excelService.getByBatchNum(filter.getBatchNum());
     /*   for (ExcelDataEntity entity : byBatchNum) {
            String cell6 = entity.getCell6();
            if(StringUtils.isNotBlank(cell6)){
                String[] userIds = cell6.split(",");
                String names = "";
                for (String userId : userIds) {
                    SysUser user = sysUserService.getById(userId);
                    if (ObjectUtils.isNotBlank(user)) {
                        names = names + user.getName() + ",";
                    }
                }
                entity.setCell1(names);
            }
        }*/

        Collections.reverse(byBatchNum);
        return  coverJqGrid(filter,byBatchNum);
    }


    /**
     * 内部立项-修改
     * @param model
     * @return
     */
    @RequestMapping(value = "/insideEdit", method = RequestMethod.GET)
    public String insideEdit(Model model,String batchNum) {
       /* System.out.println(id);
        ExcelDataEntity ent = excelService.getById(id);

        String cell6 = ent.getCell6();
        String depts = getLeaderName(cell6);
        ent.setCell1(depts);*/

       /* String cell7 = ent.getCell7();
        String xiebanNames = getdeptName(cell7);
        ent.setCell2(xiebanNames);*/

        ExcelDataEntity ent =new ExcelDataEntity();
        ent.setBatchNum(batchNum);
                model.addAttribute("excelData",ent);
        return "/modules/task/insideExcel/edit_form";
    }


    /**
     * 攻坚任务打开 查询表格
     */
    @RequestMapping(value = "/gongjiantask")
    public String gongJianTaskView(Model model){

        // model.addAttribute("deptId", SysUserUtils.getDeptId());
        return "/modules/task/gongjianExcelData/query";
    }


    /**
     * 攻坚任务导入-修改打开
     * @param model
     * @return
     */
    @RequestMapping(value = "/showgjeditview", method = RequestMethod.GET)
    public String showGongJianEditView(Model model,String batchNum) {
       /* System.out.println(id);
        ExcelDataEntity ent = excelService.getById(id);

        String cell6 = ent.getCell6();
        String depts = getLeaderName(cell6);
        ent.setCell1(depts);*/

       /* String cell7 = ent.getCell7();
        String xiebanNames = getdeptName(cell7);
        ent.setCell2(xiebanNames);*/

        //所有督察组
        SysDeptFilter sysDeptFilter = new SysDeptFilter();
        sysDeptFilter.setDeptRelation("/01/");
        List<SysDept> depts = sysDeptService.query(sysDeptFilter);
        List<SysDept> deptForModel = new ArrayList<>();
        for (SysDept sysDept:depts){
            if(!"攻坚作战室".equals(sysDept.getDeptName())&&!"县领导".equals(sysDept.getDeptName())) {
                deptForModel.add(sysDept);
            }
        }
        model.addAttribute("groups",deptForModel);   //sysId
        ExcelDataEntity ent =new ExcelDataEntity();
        ent.setBatchNum(batchNum);
        model.addAttribute("excelData",ent);
        return "/modules/task/gongjianExcelData/edit_form";
    }



    /**
     * 攻坚任务导入
     * @param excelFile
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/importgjtask", method = RequestMethod.POST)
    public Message importGongJianTask(@RequestParam MultipartFile excelFile, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        String name = excelFile.getOriginalFilename();
        String msg="";
        List<ExcelDataEntity> excelDataEntities =null;
        HashMap<String ,Object> resultMap = new HashMap<>();
        List<String> failLst = new ArrayList<>();
        if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
            System.out.println("文件不是excel类型");
            return coverMessage("500", "文件类型错误");
        } else {

            try {
                excelDataEntities = excelService.readDataOfGongJian(excelFile.getInputStream(), null);

                excelDataEntities  = excelService.saveDataGongJian(excelDataEntities);

            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
            List<ExcelDataEntity> collect = excelDataEntities.stream().filter(entity -> entity.getFlags() == 0).collect(Collectors.toList());
            collect.forEach(entity -> {
                failLst.add(entity.getSysId());
            });
            msg = redisService.get("gongjianBatch:" + SysUserUtils.getUserId());//获取批次号
            resultMap.put("batchNum",msg);
            resultMap.put("failList",failLst);
            String meg = "导入成功！本次导入"+excelDataEntities.size()+"条，校验不通过"+failLst.size()+"条";
            return coverMessage("200",meg,resultMap);
        }
    }







    @ResponseBody
    @RequestMapping(value = "/gongjian/excel/{projectType}",method = RequestMethod.GET)
    public void exportGongjianTask(@PathVariable int projectType, HttpServletResponse reponse, HttpServletRequest request) throws IOException, InvalidFormatException {
        String currentDate = DateUtil.getCurrentDate();
        String currentTime = DateUtil.getCurrentTime();
        String filetime =currentDate+"_"+currentTime;
        filetime=filetime.replace("-","_");
        filetime=filetime.replace("_","_");
        String fileName="";
        switch (projectType)
        {
            case 1:
                fileName="征地拆迁表"+filetime+".xlsx";
                break;
            case 2:
                fileName="开工提速"+filetime+".xlsx";

            case 3:
                fileName="在建提速"+filetime+".xlsx";
                break;
            case 4:
                fileName="竣工提速"+filetime+".xlsx";
                break;
            case 5:
                fileName="招商专项项目"+filetime+".xlsx";
                break;

            default:
                return;
        }

        List<FeedBackDTO> feedBackDTOS = excelService.getnewGongjianData(projectType);
        Workbook workbook = excelService.exportGongJian(feedBackDTOS, projectType);
        OutputStream out=reponse.getOutputStream();
        reponse.setContentType("application/x-msdownload");
        reponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        workbook.write(out);
        out.close();

    }


}
